﻿using System.Configuration;
using Common.Logging.Simple;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Common.Logging.Configuration;
using System;
using System.Reflection;
using System.Linq;
using Common.Logging;
using System.IO;
namespace Wicresot.CoreTests.ConfigurationSectionTest
{
    [TestClass]
    public class ConfigurationSectionTest
    {
        [TestMethod]
        public void Test()
        {
            var file = new ExeConfigurationFileMap();

            //   file.ExeConfigFilename = "test.config";

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            var f = new FactoryAdapterCollection();
            var a = new AdapterArgCollection();
            a.Add("configType", "INLINE");
            var intfs = from type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
                        where type.IsClass && !type.IsAbstract && typeof(ILoggerFactoryAdapter).IsAssignableFrom(type)
                        select type;
            int i = 0;
            for (var e = intfs.GetEnumerator(); e.MoveNext(); i++)
            {
                f[i] = new FactoryAdapterElement
                {
                    Type = e.Current,
                    Args = a,
                    Name = e.Current.Name,
                };
            }


            var data = new LogSection
                           {
                               Name = DateTime.Now.ToString(),
                               FactoryAdapters = f,
                           };


            ConfigurationSectionGroup group1 = config.SectionGroups["common"];

            if (group1 == null)
                config.SectionGroups.Add("common", group1 = new ConfigurationSectionGroup());

            var add = group1.Sections["logging"] as LogSection;

            if (add == null)
                group1.Sections.Add("logging", data);
            else
            {
                group1.Sections.Remove("logging");
                group1.Sections.Add("logging", data);

                // 或者直接修改原配置对象，前提是类型转换要成功。

                //ConfigSectionData configData = add as ConfigSectionData;

                //configData.Id = data.Id;

                //configData.Time = data.Time;
            }
            var path = string.Format(@"{0}.Temp.config", config.FilePath);
            Console.Write(path);
            config.SaveAs(path, ConfigurationSaveMode.Full);
        }
    }
}